from flask_restful import Resource, reqparse

from restful.api__.session import  login_required_current_user_generate, pid_required_target_post_generate
from restful.model.delete import DeleteInstance
from restful.model.query import QueryOneInstance, QueryMultipleRelatedInstances
from restful.model.tables import Blog, Check, Comment
from restful.model.update import UpdateInstance
from restful.response import ResponseSuccess, ResponseForbidden

def NewPost(uid,data):
    post=Blog(uid=uid)
    UpdateInstance(post, data)
    UpdateInstance(Check(uid=uid, pid=post.id, checked=False,passed=False))


def DelPost(pid):
    post = QueryOneInstance(Blog, {'id': pid})
    a_comment = QueryMultipleRelatedInstances(Comment,{'pid':pid},post)

    for i in a_comment:
        DeleteInstance(i)
    DeleteInstance(post)


class PostOrUpdateOrDelete(Resource):
    @login_required_current_user_generate
    def post(self,current_user):
        parser = reqparse.RequestParser()
        parser.add_argument('sort', required=True)
        parser.add_argument('title', required=True)
        parser.add_argument('content', required=True)
        parser.add_argument('role', type=bool, required=True)
        parser.add_argument('part', type=bool, required=True)
        data = parser.parse_args()

        NewPost(current_user.id,data)

        return ResponseSuccess(msg="发布成功,待审核")

    @login_required_current_user_generate
    @pid_required_target_post_generate
    def patch(self,current_user,target_post):
        parser = reqparse.RequestParser()
        parser.add_argument('sort')
        parser.add_argument('title')
        parser.add_argument('content')
        parser.add_argument('role', type=bool)
        parser.add_argument('part', type=bool)
        data= parser.parse_args()

        if current_user.id != target_post.uid:
            return ResponseForbidden("无权限修改")

        UpdateInstance(target_post,data)

        return ResponseSuccess(msg="更新帖子成功")

    @login_required_current_user_generate
    @pid_required_target_post_generate
    def delete(self,target_post,current_user):
        if current_user.id != target_post.uid:
            return ResponseForbidden("无权限修改")

        DelPost(target_post.id)
        return ResponseSuccess(msg="删除成功")